package cc.eddic.practice.concurrency;


import cc.eddic.practice.concurrency.QiNiuImpl.QiNiuLogParserScwImpl;
import cc.eddic.practice.concurrency.impl.LogParserWithFuture2ScwImpl;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Collection;

@Slf4j
@SpringBootApplication
public class ConcurrencyScwApplication  implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(ConcurrencyScwApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception{

        QiNiuLogParser logParser = new QiNiuLogParserScwImpl();
        long start = System.currentTimeMillis();
        if (log.isInfoEnabled()) log.info("Hello World！");
        val folder = "D:\\CODE\\qiniulog\\2\\2023-04\\2023-04";
        val logItems = logParser.parse(folder);
        if (log.isInfoEnabled()) {
            log.info("elapsed {} ms", System.currentTimeMillis() - start);
            log.info("files : {}", logItems.size());
            log.info("total log times : {}", logItems.values().stream().mapToLong(Collection::size).sum());
            log.info("valid log items : {}", logItems.values().stream().flatMap(Collection::stream).filter(QiNiuLogItem::isValidRequest).count());
        }

//        long start = System.currentTimeMillis();
//        log.info("start");
//        executor();
//        log.info("elapsed {} ms", System.currentTimeMillis()-start);
    }
//    private void loop(){
//        for (int i = 0 ; i < LOG_FILE_COUNT;i++){
//            dummyParse(i);
//        }
//    }
//
//    private void executor(){
//        ExecutorService executorService = Executors.newFixedThreadPool(128);
//        CountDownLatch latch = new CountDownLatch(LOG_FILE_COUNT);
//        for (int i = 0 ; i < LOG_FILE_COUNT ; i++){
//            int finalI = i;
//            executorService.submit(() -> dummyParse(finalI,latch));
//        }
//        try {
//            latch.await();
//        }catch (InterruptedException e ){
//            log.error(e.getMessage());
//        }
//        ExecutorServiceUtil.shutdown(executorService);
//    }
//
//    private  void dummyParse(int i ,CountDownLatch latch){
//        dummyParse(i);package cc.eddic.practice.concurrency.impl;
//
//import cc.eddic.practice.concurrency.ExecutorServiceUtil;
//import cc.eddic.practice.concurrency.LogItem;
//import cc.eddic.practice.concurrency.LogParser;
//
//import java.io.BufferedReader;
//import java.io.File;
//import java.io.FileReader;
//import java.io.IOException;
//import java.util.*;
//import java.util.concurrent.CountDownLatch;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//
//import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;
//
//
//public class LogParserWithExecutorVer1ScwImpl implements LogParser {
//
//    private static final int LOG_FILE_COUNT = 256;
//
//    public void executor(String folderName){
//        ExecutorService executorService = Executors.newFixedThreadPool(128);
//        CountDownLatch latch = new CountDownLatch(LOG_FILE_COUNT);
//        for (int i = 0 ; i < LOG_FILE_COUNT ; i++){
//            int finalI = i;
//            executorService.submit(() -> dummyParse(folderName,latch));
//        }
//        try {
//            latch.await();
//        }catch (InterruptedException e ){
//            log.error(e.getMessage());
//        }
//        ExecutorServiceUtil.shutdown(executorService);
//    }
//
//    private  void dummyParse(String folderName ,CountDownLatch latch){
//        parse(folderName);
//        latch.countDown();
//    }
//
//
//    @Override
//    public Map<String, List<LogItem>> parse(String folderName) {
//        Map<String, List<LogItem>> resultMap = new HashMap<>();
//        File fileFolder = new File(folderName);
//        traverseFolder(fileFolder, resultMap);
//        return resultMap;
//    }
//
//    private List<LogItem> parseLogFile(String path) throws IOException {
//        List<LogItem> logItems = new ArrayList<>();
//        LogItemParserScwImpl logItemParser = new LogItemParserScwImpl();
//        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
//            String line;
//            while ((line = reader.readLine()) != null) {
//                Optional<LogItem> parsedLogItem = logItemParser.parse(line);
//                parsedLogItem.ifPresent(logItems::add);
//            }
//        }
//        return logItems;
//    }
//
//    private void traverseFolder(File fileFolder, Map<String, List<LogItem>> resultMap) {
//        File[] files = fileFolder.listFiles();
//        if (files != null) {
//            for (File file : files) {
//                if (file.isDirectory()) {
//                    traverseFolder(file, resultMap);
//                } else if (file.getName().endsWith(".log")) {
//                    try {
//                        List<LogItem> logItems = parseLogFile(file.getAbsolutePath());
//                        resultMap.put(file.getAbsolutePath(), logItems);
//                    } catch (IOException e) {
//                        throw new RuntimeException(e);
//                    }
//                }
//            }
//        }
//    }
//}
//        latch.countDown();
//    }
//
//
//    private void dummyParse(int i){
//        try {
////            val r = rnd(10,50);
//            int r = 10;
//            if (log.isInfoEnabled())log.info("{} => sleep {} ms",i,r);
//            Thread.sleep(r);
//        }catch (InterruptedException e ){
//            log.error(e.getMessage());
//        }
//    }
//
//    private  int rnd (int min ,int max ){
//        return random.nextInt(max - min + 1) + min;
//    }
//
//    private final  int LOG_FILE_COUNT = 256;
//    private final Random random = new Random(System.currentTimeMillis());



//    public ConcurrencyScwApplication(@Qualifier("LogParserWithLoopImpl")LogParser logParser){
//        this.logParser = logParser;
//    }
//    private final LogParser logParser;
}
